using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace CKS.EWE.WikiDiscussion
{
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:DiscussionAlertButton runat=server></{0}:DiscussionAlertButton>")]
	public class DiscussionAlertButton : FormButton
	{
        // Create the "Alert Me" or "Edit Alert" button used on the Wiki Discussion view page.
        // Instance specified in control template SharePoint:RenderingTemplate ID="DiscussionMiniConsole"
        
        protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			SPContext context = SPContext.GetContext(HttpContext.Current);
			Guid listId = context.List.ID;
			string source = SPEncode.UrlEncode(HttpContext.Current.Request.Url.ToString());
			string rootFolder = HttpContext.Current.Request.QueryString["RootFolder"];
			rootFolder = SPHttpUtility.HtmlDecode(rootFolder);
			SPAlert alert = GetAlert(context, rootFolder);

			if (alert == null)
			{
                int itemId = GetDiscItem(context.List, rootFolder);
				Text = "Alert Me";
				NavigateUrl = String.Format("{0}/_layouts/SubNew.aspx?List={{{1}}}&ID={2}&Source={3}", context.Web.ServerRelativeUrl, listId, itemId, source);
			}
			else
			{
				Text = "Edit Alert";
				NavigateUrl = String.Format("{0}/_layouts/SubEdit.aspx?Alert={{{1}}}&List={{{2}}}&Source={3}", context.Web.ServerRelativeUrl, alert.ID, listId, source);
			}
		}

		private static SPAlert GetAlert(SPContext context, string rootFolder)
		{
			string key = "filterpath";
			string filterPathValue = rootFolder.Substring(1);
      SPUser currentUser = context.Web.CurrentUser;
      if (currentUser != null)
      {
        foreach (SPAlert alert in currentUser.Alerts)
        {
          if (alert.Properties.ContainsKey(key) && alert.Properties[key] == filterPathValue)
          {
            return alert;
          }
        }
      }

			return null;
		}

		// TODO: Look if there's a way of finding an item by key rather than looping over the folders.
		private static int GetDiscItem(SPList discList, string rootFolder)
		{
			int itemId = -1;
			foreach (SPListItem item in discList.Folders)
			{
				if (item.Folder.ServerRelativeUrl == rootFolder)
				{
					itemId = item.ID;
					break;
				}
			}
			return itemId;
		}
	}
}